package com.example.sharesinfo.fragment.index;


import android.graphics.Color;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import lecho.lib.hellocharts.formatter.ColumnChartValueFormatter;
import lecho.lib.hellocharts.formatter.SimpleColumnChartValueFormatter;
import lecho.lib.hellocharts.listener.ColumnChartOnValueSelectListener;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Column;
import lecho.lib.hellocharts.model.ColumnChartData;
import lecho.lib.hellocharts.model.SubcolumnValue;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.view.ColumnChartView;

import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sharesinfo.R;
import com.example.sharesinfo.adapter.ScrollablePanelAdapter;
import com.example.sharesinfo.model.ColumnTitle;
import com.example.sharesinfo.model.DataInfo;
import com.example.sharesinfo.model.HKStockModel;
import com.example.sharesinfo.model.PanMainModel;
import com.example.sharesinfo.model.StockInfo;
import com.example.sharesinfo.utils.LogUtils;
import com.example.sharesinfo.utils.OkHttpUtils;
import com.example.sharesinfo.utils.TimeUtils;
import com.kelin.scrollablepanel.library.ScrollablePanel;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.sql.Time;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class QuotationFragment extends Fragment {
    private static final String LOGTAG = "QuotationFragment:";
    private static final int GetPanMianSuccess = 1001;
    private static final int GetPanMianFailed = 1002;
    private static final int GetGetYiDongSuccess = 1003;
    private static final int GetGetYiDongFailed = 1004;
    private TextView stock_quotation_date;
    private TextView stock_quotation_grade;
    private TextView stock_quotation_score;
    private TextView stock_quotation_number_of_rose;
    private TextView stock_quotation_number_of_down;
    private TextView stock_quotation_hot_plate;
    private TextView stock_advice;
    //柱状图
    private ColumnChartView chart;
    private List<String> value = new ArrayList<>();
    //
    private ScrollablePanel scrollablePanel;
    private ScrollablePanelAdapter scrollablePanelAdapter;
    private List<PanMainModel> mList = new ArrayList<>();

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case GetPanMianSuccess:
                    JSONObject result = (JSONObject) msg.obj;
                    try {
                        stock_quotation_grade.setText("盘面评分：" + result.getString("盘面评分"));
                        stock_quotation_score.setText(result.getString("大盘评级"));
                        stock_quotation_number_of_rose.setText(result.getString("涨家数"));
                        stock_quotation_number_of_down.setText(result.getString("跌家数"));
                        stock_quotation_hot_plate.setText(result.getString("热门板块"));
                        stock_advice.setText("投资建议：" + result.getString("投资建议"));
                        value.add(result.getString("跌停~-8%"));
                        value.add(result.getString("-8%~-6%"));
                        value.add(result.getString("-6%~-4%"));
                        value.add(result.getString("-4%~-2%"));
                        value.add(result.getString("-2%~0%"));
                        value.add(result.getString("0%~2%"));
                        value.add(result.getString("2%~4%"));
                        value.add(result.getString("4%~6%"));
                        value.add(result.getString("6%~8%"));
                        value.add(result.getString("8%~涨停"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    generateData();
                    break;
                case GetPanMianFailed:
                    break;
                case GetGetYiDongSuccess:
                    if (mList.size() > 0) {
                        mList.clear();
                    }
                    JSONArray resultList = (JSONArray) msg.obj;
                    for (int i = 0; i < resultList.length(); i++) {
                        PanMainModel model = new PanMainModel();
                        try {
                            JSONObject object = (JSONObject) resultList.get(i);
                            model.setMkmc(object.getString("板块名称"));
                            model.setZdf(object.getString("涨跌幅"));
                            model.setZljlr(object.getString("主力净流入"));
                            model.setMkydzcs(object.getString("板块异动总次数"));
                            if (object.has("快速反弹")) {
                                model.setKsft(object.getString("快速反弹"));
                            } else {
                                model.setKsft("-");
                            }
                            model.setType(object.getString("板块异动最频繁个股及所属类型"));
                            if (object.has("高台跳水")) {
                                model.setGtts(object.getString("高台跳水"));
                            } else {
                                model.setGtts("-");
                            }
                            model.setType(object.getString("板块异动最频繁个股及所属类型"));
                            if (object.has("大笔买入")) {
                                model.setJsxd(object.getString("大笔买入"));
                            } else {
                                model.setJsxd("-");
                            }
                            mList.add(model);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        generateTestData(mList);
                    }
                    break;
                case GetGetYiDongFailed:
                    break;
                case 404:
                    break;
            }
            return false;
        }
    });

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_quotation, null);
        initView(view);
        initData();
        getPanMian();
        return view;
    }

    private void initView(View view) {
        chart = view.findViewById(R.id.ccv);
        chart.setOnValueTouchListener(new ColumnChartOnValueSelectListener() {
            @Override
            public void onValueSelected(int i, int i1, SubcolumnValue subcolumnValue) {
                Toast.makeText(getContext(), "i:" + i + ",i1:" + i1, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onValueDeselected() {
                Toast.makeText(getContext(), "黑人???", Toast.LENGTH_SHORT).show();
            }
        });

        stock_quotation_date = view.findViewById(R.id.stock_quotation_date);
        stock_quotation_date.setText("数据更新于" + TimeUtils.getNowTime());
        stock_quotation_grade = view.findViewById(R.id.stock_quotation_grade);
        stock_quotation_score = view.findViewById(R.id.stock_quotation_score);
        stock_quotation_number_of_rose = view.findViewById(R.id.stock_quotation_number_of_rose);
        stock_quotation_number_of_down = view.findViewById(R.id.stock_quotation_number_of_down);
        stock_quotation_hot_plate = view.findViewById(R.id.stock_quotation_hot_plate);
        stock_advice = view.findViewById(R.id.stock_advice);
        scrollablePanel = view.findViewById(R.id.sp_pan);
        scrollablePanelAdapter = new ScrollablePanelAdapter(1, new ScrollablePanelAdapter.OnBindDataListener() {
            @Override
            public void onBindViewHolder(RecyclerView.ViewHolder holder, int row, int column) {
                int viewType = scrollablePanelAdapter.getItemViewType(row, column);
                switch (viewType) {
                    case ScrollablePanelAdapter.COLUMN_TITLE_TYPE:
                        scrollablePanelAdapter.setColumnTitleView(column, (ScrollablePanelAdapter.ColumnTitleViewHolder) holder);
                        break;
                    case ScrollablePanelAdapter.STOCK_TYPE:
                        scrollablePanelAdapter.setStockView(row, (ScrollablePanelAdapter.StockViewHolder) holder);
                        break;
                    case ScrollablePanelAdapter.DATA_TYPE:
                        scrollablePanelAdapter.setDataView(row, column, (ScrollablePanelAdapter.DataViewHolder) holder);
                        break;
                    case ScrollablePanelAdapter.TITLE_TYPE:
                        break;
                }

            }
        });
        scrollablePanel.setPanelAdapter(scrollablePanelAdapter);
        querydatas(1);
    }

    private void generateData() {
        //一个柱状图需要一个柱子集合
        List<Column> columnList = new ArrayList<>();
        //每根柱子又可以分为多根柱子
        List<SubcolumnValue> subcolumnValueList;
        int columns = 10;//一共7根柱子
        int subColumn = 1;//每根柱子的子柱子为1根
        for (int i = 0; i < columns; i++) {
            subcolumnValueList = new ArrayList<>();
            if (i <= 4) {
                for (int j = 0; j < subColumn; j++) {
                    //每根子柱子需要一个值和颜色
                    subcolumnValueList.add(new SubcolumnValue(Float.parseFloat(value.get(i)), Color.GREEN));
                }
            } else {
                for (int j = 0; j < subColumn; j++) {
                    //每根子柱子需要一个值和颜色
                    subcolumnValueList.add(new SubcolumnValue(Float.parseFloat(value.get(i)), Color.RED));
                }
            }

            //每根柱子需要一个子柱子集合
            Column column = new Column(subcolumnValueList);
            //这一步是能让圆柱标注数据显示带小数的重要一步
            ColumnChartValueFormatter chartValueFormatter = new SimpleColumnChartValueFormatter(2);
            column.setFormatter(chartValueFormatter);
            column.setHasLabels(true);//是否直接显示标注（其它的一些设置类似折线图）
            columnList.add(column);
        }
        ColumnChartData data = new ColumnChartData(columnList);
        Axis axisX = new Axis();
        Axis axisY = new Axis().setHasLines(true);
        axisX.setName("  ");
        axisY.setName("出场率%");
        axisY.hasLines();//是否显示网格线
        axisY.setTextColor(Color.BLACK);//颜色

        //给轴设置值
        List<AxisValue> list = new ArrayList<>();
        list.add(new AxisValue(0).setLabel("跌停~-8%"));
        list.add(new AxisValue(1).setLabel("-8%~-6%"));
        list.add(new AxisValue(2).setLabel("-6%~-4%"));
        list.add(new AxisValue(3).setLabel("-4%~-2%"));
        list.add(new AxisValue(4).setLabel("-2%~0%"));
        list.add(new AxisValue(5).setLabel("0%~2%"));
        list.add(new AxisValue(6).setLabel("2%~4%"));
        list.add(new AxisValue(7).setLabel("4%~6%"));
        list.add(new AxisValue(8).setLabel("6%~8%"));
        list.add(new AxisValue(9).setLabel("8%~涨停"));
        //底部标注是否斜着显示
        axisX.setHasTiltedLabels(true);
        //给x轴设置值
        axisX.setValues(list);
        data.setAxisXBottom(axisX);
        //设置是否让多根子柱子在同一根柱子上显示（会以断层的形式分开），由于这里子柱子只有一根，故设置true也无意义，读者可自行尝试
        data.setStacked(false);
        chart.setColumnChartData(data);
    }

    private void querydatas(int page) {
        String url = "http://119.23.221.142/api/stock/GetYiDongInfo?Page=1";
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            Message message = mHandler.obtainMessage();

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                JSONObject object = new JSONObject(s);
                if (object.getString("code").equals("200")) {
                    message.what = GetGetYiDongSuccess;
                    message.obj = object.getJSONArray("data");
                    mHandler.sendMessage(message);
                } else {
                    message.what = GetGetYiDongFailed;
                    mHandler.sendMessage(message);
                }

            }

            @Override
            public void OnFailed(String s) {
                message.what = 404;
                message.obj = s;
                mHandler.sendMessage(message);
            }
        });
    }

    private void initData() {
        List<ColumnTitle> columnTitleList = new ArrayList<>();
        String column2 = "涨跌幅";
        ColumnTitle title2 = new ColumnTitle();
        title2.setColumnTitle(column2);
        String column3 = "快速反弹";
        ColumnTitle title3 = new ColumnTitle();
        title3.setColumnTitle(column3);
        String column4 = "高台跳水";
        ColumnTitle title4 = new ColumnTitle();
        title4.setColumnTitle(column4);
        String column5 = "大笔买入";
        ColumnTitle title5 = new ColumnTitle();
        title5.setColumnTitle(column5);
        String column6 = "主力净流入";
        ColumnTitle title6 = new ColumnTitle();
        title6.setColumnTitle(column6);
        String column7 = "异动总次数";
        ColumnTitle title7 = new ColumnTitle();
        title7.setColumnTitle(column7);
        String column8 = "所属类型";
        ColumnTitle title8 = new ColumnTitle();
        title8.setColumnTitle(column8);
        columnTitleList.add(title2);
        columnTitleList.add(title3);
        columnTitleList.add(title4);
        columnTitleList.add(title5);
        columnTitleList.add(title6);
        columnTitleList.add(title7);
        columnTitleList.add(title8);
        scrollablePanelAdapter.setColumnTitleList(columnTitleList);
    }

    private void generateTestData(List<PanMainModel> list) {
        List<StockInfo> stockInfoList = new ArrayList<>();
        List<List<DataInfo>> dataList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            PanMainModel model = list.get(i);
            StockInfo stockInfo = new StockInfo();
            stockInfo.setStockName(model.getMkmc());
            stockInfo.setRoomId(i);
            stockInfo.setStockId("");
            stockInfoList.add(stockInfo);
            addData(model, dataList);
        }
        scrollablePanelAdapter.setStockInfoList(stockInfoList);
        scrollablePanelAdapter.setDataList(dataList);
        scrollablePanel.notifyDataSetChanged();
    }

    private void addData(PanMainModel model, List<List<DataInfo>> dataList) {
        List<DataInfo> dataInfoList = new ArrayList<>();
        DataInfo dataInfo1 = new DataInfo();
        dataInfo1.setData(model.getZdf());
        dataInfoList.add(dataInfo1);

        DataInfo dataInfo2 = new DataInfo();
        dataInfo2.setData(model.getKsft());
        dataInfoList.add(dataInfo2);

        DataInfo dataInfo3 = new DataInfo();
        dataInfo3.setData(model.getGtts());
        dataInfoList.add(dataInfo3);

        DataInfo dataInfo4 = new DataInfo();
        dataInfo4.setData(model.getJsxd());
        dataInfoList.add(dataInfo4);

        DataInfo dataInfo5 = new DataInfo();
        dataInfo5.setData(model.getZljlr());
        dataInfoList.add(dataInfo5);

        DataInfo dataInfo6 = new DataInfo();
        dataInfo6.setData(model.getMkydzcs());
        dataInfoList.add(dataInfo6);

        DataInfo dataInfo7 = new DataInfo();
        dataInfo7.setData(model.getType());
        dataInfoList.add(dataInfo7);

        dataList.add(dataInfoList);
    }

    /**
     * 沪深涨跌分布 无参数
     */
    private void getPanMian() {
        String url = "http://119.23.221.142/api/stock/GetPanMian";
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {
            Message message = mHandler.obtainMessage();

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                JSONObject object = new JSONObject(s);
                if (object.getString("code").equals("200")) {
                    message.what = GetPanMianSuccess;
                    message.obj = object.getJSONObject("data");
                    mHandler.sendMessage(message);
                } else {
                    message.what = GetPanMianFailed;
                    mHandler.sendMessage(message);
                }
            }

            @Override
            public void OnFailed(String s) {
                message.what = 404;
                message.obj = s;
                mHandler.sendMessage(message);
            }
        });
    }


}
